package com.xian.ucenter.controller.admin;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xian.ucenter.commons.Result;
import com.xian.ucenter.entities.Post;
import com.xian.ucenter.entities.Project;
import com.xian.ucenter.entities.vo.PostQuery;
import com.xian.ucenter.service.ProjectService;
import com.xian.ucenter.service.impl.ProjectServiceImpl;
import com.xian.ucenter.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xian
 * @since 2022/07/23 02:59
 */
@RestController
@RequestMapping("/ucenter/admin/project")
public class ProjectController {
    @Autowired
    private ProjectServiceImpl projectService;

    @Resource
    private PageUtil<Project> projectPageUtil;

    @PostMapping("/save")
    public Result save (@RequestBody Project project) {
        return projectService.updateById(project)?Result.ok():Result.fail();
    }

    @PostMapping("/create")
    public Result create (@RequestBody Project project) {
        return projectService.save(project) ? Result.ok():Result.fail();
    }

    @GetMapping("/{projectId}")
    public Result getPost (@PathVariable("projectId") String projectId) {
        Project project = projectService.getById(projectId);
        if (ObjectUtil.isNull(project))
            throw new RuntimeException("帖子不存在");
        return Result.ok("project",project);
    }

    @PostMapping("/search/{current}/{count}")
    public Result getPost (@PathVariable("current") Integer current, @PathVariable("count") Integer count, @RequestBody(required = false) Project project) {
        QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(project)) {
            String name = project.getName();
            Integer status = project.getStatus();
            Date begin = project.getCreateTime();
            Date end = project.getModifyTime();
            if (StringUtils.hasText(name)) {
                projectQueryWrapper.like("name",name);
            } else if (ObjectUtil.isNotNull(status)) {
                projectQueryWrapper.eq("status",status);
            } else if (ObjectUtil.isNotNull(begin)) {
                projectQueryWrapper.lt("create_time",begin);
            } else if (ObjectUtil.isNotNull(end)) {
                projectQueryWrapper.gt("create_time",end);
            }
        }
        return projectPageUtil.pageList(current,count,projectService,projectQueryWrapper);
    }

    @GetMapping("/del/{projectId}")
    public Result delPost (@PathVariable("projectId") String projectId) {
        return projectService.removeById(projectId)?Result.ok():Result.fail();
    }

}
